package com.jie.pen;

import com.jie.common.Denlong;
import com.jie.show.User;
import com.jie.service.UserService;
import org.aspectj.org.eclipse.jdt.internal.formatter.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     *
     * @param user 前端传过来的User数据，前端的属性必须跟Java实体类保持一致 ：
     *             {
     *             "account":"pyhan",
     *             "password":"123456"
     *             }
     * @return
     * @PostMapping 接口映射 前端发起POST请求 基于类上边的拼接 => http://localhost:8080/api/user/login
     * @RequestBody 使用这个注解接收请求中BODY的参数
     */
    @PostMapping("/login")
    public Denlong login(@RequestBody User user) {
        //调用UserService的登录方法
        User loginUser = userService.login(user);
        //返回null说明账号或密码错误，否则就是成功
        if (loginUser == null) {
            return Denlong.create(0, "登录失败", null);
        } else {
            return Denlong.create(1, "登录成功", loginUser);
        }
    }

    /**
     * 用户注册接口   http://localhost:8080/api/user/register
     *
     * @param user 参数是前端传过来的JSON对象，同上
     * @return
     */
    @PostMapping("/register")
    public Denlong register(@RequestBody User user) {
        User registerUser = userService.register(user);
        if (registerUser == null) {
            return Denlong.create(0, "注册失败", null);
        } else {
            return Denlong.create(1, "注册成功", user);
        }
    }

    @GetMapping("/token/test")
    public Denlong token(HttpServletRequest request) {
        User user = userService.getUserByToken(request);
        if (user == null) {
            return Denlong.create(0, "失败", null);
        } else {
            return Denlong.create(1, "成功", user);

        }
    }
}
